﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using SendMailServer.Search;

namespace SendMailServer
{
    internal class MaxKBConenction: IConnection
    {
        public static MyChatGptConfig m_config = new MyChatGptConfig();

        private string m_lastPostUrl;

        public string LastPostUrl => m_lastPostUrl;

        #region 初始化
        public ResMsg Load(string key)
        {
            try
            {
                m_config.Load();
                return null;
            }
            catch (Exception err)
            {
                return new ResMsg()
                {
                    MsgCode = key,
                    IsOk = false,
                    Content = "读取AI的本地配置错误" + err.Message + "," + err.StackTrace,
                    UseSelfResponse = true
                };
            }
        }
        public ResMsg Reload(string key)
        {
            if (m_config.IsLoaded == 9)
            {
                m_config.ChatId = GetChatId(key, out ResMsg e2);
                if (m_config.ChatId == null)
                {
                    return e2;
                }
                m_config.Save();
            }
            return null;
        }
        public string GetChatId(string currentKey, out ResMsg errMesg)
        {
            string url = string.Format("http://{0}:{1}/api/application/profile", m_config.ChatGptIP, m_config.ChatGptPort);

            try
            {
                errMesg = null;

                Logger.WriteLine("ChatGpt:希望获得新的chatID");
                Logger.WriteLine("ChatGpt:希望获得新的chatID" + url);

                string result = "";
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "Get";
                req.ContentType = "application/json";

                this.SetHttpWebRequest(req);

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
                Logger.WriteLine("ChatGpt:希望获得新的chatID:结果" + result);
                var oldAttr = (JToken)JsonConvert.DeserializeObject(result as string);
                Logger.WriteLine("ChatGpt:希望获得新的chatID:结果" + oldAttr["data"]["id"].ToString());
                return oldAttr["data"]["id"].ToString();
            }
            catch (Exception err)
            {
                errMesg = new ResMsg()
                {
                    MsgCode = currentKey,
                    IsOk = true,
                    Content = "GetChatId 失败" + url + "," + err.Message,
                    UseSelfResponse = true
                };
            }
            return null;
        }
        #endregion

        #region 新话题
        public ResMsg CreateNewTopic(JToken oldAttr, string userName, string key)
        {
            var m_userTopicId = ChatGpt.m_userTopicId;

            if (oldAttr["query"].ToString() == "newtopic")
            {
                if (m_userTopicId.ContainsKey(userName))
                {
                    m_userTopicId.Remove(userName);
                }
                var newTopicStr = "";
                string topicUrl = "";
                try
                {
                    newTopicStr = NewTopic(out topicUrl);
                }
                catch (Exception err)
                {
                    return new ResMsg()
                    {
                        MsgCode = key,
                        IsOk = true,
                        Content = "设置新话题失败" + topicUrl + "," + err.Message,
                        UseSelfResponse = true
                    };
                }
                m_userTopicId.Add(userName, newTopicStr);
                Logger.WriteLine("AddUserTopic" + m_userTopicId[userName]);
                return new ResMsg()
                {
                    MsgCode = key,
                    IsOk = true,
                    Content = "设置新话题成功" + m_userTopicId[userName],
                    UseSelfResponse = true
                };
            }
            return null;
        }
        private string NewTopic(out string topicUrl)
        {
            topicUrl = string.Format("http://{0}:{1}/api/application/{2}/chat/open?application_id={2}",
                m_config.ChatGptIP, m_config.ChatGptPort, m_config.ChatId);

            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(topicUrl);
            req.Method = "Get";
            req.ContentType = "application/json";

            this.SetHttpWebRequest(req);

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            var oldAttr = (JToken)JsonConvert.DeserializeObject(result as string);
            return oldAttr["data"].ToString();
        }
        #endregion

        #region MyRegion
        public void ChatAsync(string msg, string userName, string key, EventHandler handler)
        {
            var topicId = GetTopicOrConversationId(userName);

            var postUrl = string.Format("http://{0}:{1}/api/application/chat_message/" + topicId, m_config.ChatGptIP, m_config.ChatGptPort);

            m_lastPostUrl = postUrl;

            var str = Post(postUrl, msg);
            var str2 = FormatResult(str, out string recordId);
            var str3 = GetReference(topicId, recordId);

            if (string.IsNullOrEmpty(str2))
            {
                str2 = "查询网站" + postUrl + ":" + msg + "，没有得到消息";
            }
            if (string.IsNullOrEmpty(str3))
            {
                str3 = "查询网站" + topicId + ":" + recordId + "没有得到消息";
            }
            return;

            /*return new ResMsg()
            {
                MsgCode = key,
                IsOk = true,
                Content = str2 + "<ref>" + str3,
                UseSelfResponse = true
            };*/
        }
        private string GetRequestMsg(JToken oldJKen)
        {
            var msg = oldJKen["query"];
            var chatMsg = "{ \"message\":\"" + msg + "\",\"re_chat\":false}";
            return chatMsg;
        }
        private string GetTopicOrConversationId(string userName)
        {
            var m_userTopicId = ChatGpt.m_userTopicId;
            var topicId = m_userTopicId.ContainsKey(userName) ? m_userTopicId[userName] : "78f60052-5ba1-11ef-8c0a-0242ac110003";
            return topicId;
        }
        #endregion
        /// <summary>
        /// 指定Post地址使用Get 方式获取全部字符串
        /// </summary>
        /// <param name="url">请求后台地址</param>
        /// <returns></returns>
        public string Post(string url, string dic)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/json";

            SetHttpWebRequest(req);


            byte[] data = Encoding.UTF8.GetBytes(dic);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }


        public void SetHttpWebRequest(HttpWebRequest req)
        {
            req.Headers.Add("AUTHORIZATION: " + m_config.ApiKey);
        }

       
        public string FormatResult(string str, out string recordId)
        {
            var lines = StringSplit(str, "data:");
            recordId = "";
            StringBuilder stringBuilder = new StringBuilder();
            for (var i = 0; i < lines.Count; i++)
            {
                if (string.IsNullOrEmpty(lines[i])) continue;
                var oldAttr = (JToken)JsonConvert.DeserializeObject(lines[i] as string);
                stringBuilder.Append(oldAttr["content"].ToString());
                if (string.IsNullOrEmpty(recordId))
                {
                    recordId = oldAttr["id"].ToString();
                }
            }
            return stringBuilder.ToString();
        }
        private List<string> StringSplit(string str, string split)
        {
            List<string> res = new List<string>();
            var t = str.IndexOf(split);
            int lastT = 0;
            while (t >= 0)
            {
                res.Add(str.Substring(lastT, t - lastT));
                t += split.Length;
                lastT = t;
                t = str.IndexOf(split, t);
            }
            return res;
        }

        public string GetReference(string topicId, string recordId)
        {
            string url = string.Format("http://{0}:{1}/api/application/{2}/chat/", m_config.ChatGptIP, m_config.ChatGptPort, m_config.ChatId) + topicId + "/chat_record/" + recordId;

            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "Get";
            req.ContentType = "application/json";

            this.SetHttpWebRequest(req);

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            var oldAttr = (JToken)JsonConvert.DeserializeObject(result as string);
            return oldAttr["data"].ToString();
        }

        
    }
    internal class MyChatGptConfig
    {
        public string ChatGptIP { get; set; } = "172.18.3.102";
        public string ChatGptPort { get; set; } = "8080";
        public string chatMessageUrl { get; set; } = "/api/application/chat_message/";
        public string ApiKey { get; set; } = "application-67449aa2b1ce38f4d52cacfcd78e8bab";
        public string ChatId { get; set; } = "88dd5814-7184-11ef-a1d7-0242ac110003";

        public int IsLoaded { get; set; } = 0;

        public void Save()
        {
            var fileName = "D:\\Program Files\\SendMailServer\\mychatgpt.ini";
            File.WriteAllLines(fileName, new string[]
            {
                ChatGptIP,
                ChatGptPort,
                chatMessageUrl,
                ApiKey,
                ChatId
            });
        }

        public void Load()
        {
            if (IsLoaded > 0)
            {
                IsLoaded--;
                return;
            }
            var fileName = "D:\\Program Files\\SendMailServer\\mychatgpt.ini";
            if (File.Exists(fileName))
            {
                var lines = File.ReadAllLines(fileName);
                ChatGptIP = lines[0].Trim();
                ChatGptPort = lines[1].Trim();
                chatMessageUrl = lines[2].Trim();
                ApiKey = lines[3].Trim();
                ChatId = lines[4].Trim();
            }
            else
            {
                Save();
            }
            IsLoaded = 10;
        }
    }
}
